/**
 * TimeFormat.java
 * @author: liuex
 * 2007-12-30 ����04:25:19
 *
 * note: 
 */
package org.lex.utils.text;

public class TimeFormat {
	private static final int DEFAULT_PRECISION = 2;
	private static final char SEPARATOR = ':';
	private static final long MS = 1000;
	private static final long SECONDS = 60;
	private static final long MINUTES = 60;

	public static String format(long millis) {
		return format(millis, DEFAULT_PRECISION, new StringBuilder()).toString();
	}

	public static String format(long millis, int precision) {
		return format(millis, precision, new StringBuilder()).toString();
	}

	public static StringBuilder format(long millis, int precision, StringBuilder dest) {
		if (null == dest)
			dest = new StringBuilder();
		long seconds = millis / MS;
		long minutes = seconds / SECONDS;
		seconds = seconds % SECONDS;
		if (minutes >= MINUTES) {
			// hour
			long hours = minutes / MINUTES;
			minutes = minutes % MINUTES;
			append(hours, dest);
			dest.append(SEPARATOR);
		}
		// minutes
		append(minutes, dest);
		dest.append(SEPARATOR);
		// seconds
		append(seconds, dest);
		// precision
		if (0 == precision)
			return dest;
		// ms
		long ms = millis % MS;
		if (0 == ms)
			return dest;
		dest.append('.');
		switch (precision) {
		case 1:
			dest.append(ms / 100L);
			break;
		case 3:
			dest.append(ms);
			break;
		case 2:// fall through
		default:
			dest.append(ms / 10L);
			break;
		}
		return dest;
	}

	private static final char[] digits = "0123456789".toCharArray();

	private static StringBuilder append(long v, StringBuilder dest) {
		if (v < 10L)
			dest.append('0').append(digits[(int) v]);
		else
			dest.append(v);
		return dest;
	}
}
